var express    = require('express');
var bodyParser = require('body-parser');
var app        = express();
var cp         = require('child_process');
var fs         = require('fs');
var iniparser  = require('iniparser');
var argv       = require( 'argv' );

var args = argv.option([
  {
    name: 'conf',
    short: 'c',
    type: 'path'
  },
  {
    name: 'port',
    short: 'p',
    type: 'int'
  }
]).run();

var repos = [];

if (fs.existsSync(args.options.conf)) {
  repos = iniparser.parseSync(args.options.conf);
}

app.use(bodyParser.urlencoded({ extended: false }));

app.get('/', function(req, res) {
  res.send('ok');
});

app.post('/:repo', function(req, res) {
  if (repos.hasOwnProperty(req.params.repo) && req.body.hasOwnProperty('hook')) {
    var repo = repos[req.params.repo];
    var hook = JSON.parse(req.body.hook);
    if (hook.password == repo.password && hook.push_data.ref == 'refs/heads/'+repo.branch && fs.existsSync(repo.path)) {
      cp.exec('git pull origin ' + repo.branch, {cwd: repo.path}, function(error, stdout, stderr) {
	if ( ! error && fs.existsSync(repo.path + 'deploy.sh')) {
          cp.execFile(repo.path + 'deploy.sh', {cwd: repo.path}, function(error, stdout, stderr) {

          });
        }
      });
    }
  }
  res.send('done');
});

app.listen(args.options.port || 3030);
